#include <stdlib.h>
#include "MIUser.h"

namespace MIUser {

int get_component(collaboration::MIUser* r, const char* name)
{
	unsigned int i=0;
	collaboration::MIComponent* aux;

	for (i=0; i<r->components.length(); i++)
	{
		aux = &(r->components[i]);
		if (strcmp(aux->name, name) == 0)
		{
			return i;
		}
	}

	return -1;
}

void is_online(collaboration::MIUser* r, CORBA::Boolean b)
{
	r->is_online = b;
	if (r->is_online)
		r->last_time_updated = time(0);
}

CORBA::Boolean has_allowed_role(collaboration::MIUser* r, const char* role)
{
	unsigned int i;
	
	if (role == NULL) return false;
	
	for(i=0; i<r->allowed_roles.length(); i++)
	{
		if (strcmp(r->allowed_roles[i], role) == 0)
			return true;
	}

	return false;
}

CORBA::Boolean add_allowed_role(collaboration::MIUser* r, const char* role)
{
	if (!has_allowed_role(r, role))
	{
		int len = r->allowed_roles.length();
		r->allowed_roles.length(len+1);
		
		r->allowed_roles[len] = CORBA::string_dup(role);

		return true;
	}

	else return false;
}

CORBA::Boolean remove_allowed_role(collaboration::MIUser* r, const char* role)
{
	char* temp;
	unsigned int i;
	for (i=0; i<r->allowed_roles.length(); i++)
	{
		if (strcmp(r->allowed_roles[i], role) == 0)
		{
			temp = r->allowed_roles[r->allowed_roles.length()-1];
			r->allowed_roles[r->allowed_roles.length()-1] = r->allowed_roles[i];
			r->allowed_roles[i] = temp;
			
			r->allowed_roles.length(r->allowed_roles.length()-1); 
			
			return true;
		}
	}

	return false;
}

CORBA::Long get_component_permissions(collaboration::MIUser* r, const char* comp_name)
{
	int pos = get_component(r, comp_name);
	if (pos != -1)
	{
		return r->components[pos].permissions;
	}

	else return -1;
}

void set_component_permissions(collaboration::MIUser* r, const char* comp_name, CORBA::Long level)
{
	int pos = get_component(r, comp_name);

	if (pos != -1)
	{
		r->components[pos].permissions = level;
	}

	else
	{
		collaboration::MIComponent* aux = new collaboration::MIComponent;
		aux->name = CORBA::string_dup(comp_name);
		aux->permissions = level;
		
		int len = r->components.length();
		r->components.length(len+1);
		r->components[len] = *aux;
	}
}

}
